package com.example.a2023110445

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class Activity3 : AppCompatActivity() {
    
    private lateinit var photoImageView: ImageView
    private val REQUEST_IMAGE_CAPTURE = 100
    private val REQUEST_CAMERA_PERMISSION = 200
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity3)
        
        photoImageView = findViewById(R.id.photoImageView)
        val cameraButton: Button = findViewById(R.id.cameraButton)
        val backButton: Button = findViewById(R.id.backButton)
        
        cameraButton.setOnClickListener {
            if (checkCameraPermission()) {
                dispatchTakePictureIntent()
            } else {
                requestCameraPermission()
            }
        }
        
        backButton.setOnClickListener {
            finish()
        }
    }
    
    private fun checkCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    private fun requestCameraPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            Toast.makeText(this, "需要相机权限来拍照", Toast.LENGTH_SHORT).show()
        }
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            REQUEST_CAMERA_PERMISSION
        )
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                dispatchTakePictureIntent()
            } else {
                Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    // 使用隐式 Intent 调用相机
    private fun dispatchTakePictureIntent() {
        // 创建隐式 Intent，ACTION_IMAGE_CAPTURE 表示要启动相机
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        
        // 检查是否有应用可以处理这个 Intent
        val resolveActivity = takePictureIntent.resolveActivity(packageManager)
        
        if (resolveActivity != null) {
            // 启动相机并等待返回结果
            try {
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                Toast.makeText(this, "正在打开相机...", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this, "无法启动相机: ${e.message}", Toast.LENGTH_LONG).show()
            }
        } else {
            // 如果模拟器没有相机，给出明确提示
            Toast.makeText(
                this, 
                "模拟器未配置相机！\n请在 AVD 设置中启用相机：\nDevice Manager -> Edit -> Show Advanced Settings -> Camera",
                Toast.LENGTH_LONG
            ).show()
        }
    }
    
    // 处理相机返回的结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        // 检查请求码和结果码
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
            // 从 Intent 的 extras 中获取照片缩略图
            val imageBitmap: Bitmap? = data?.extras?.get("data") as? Bitmap
            // 显示照片在 ImageView 中
            if (imageBitmap != null) {
                photoImageView.setImageBitmap(imageBitmap)
                Toast.makeText(this, "照片已保存", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "无法获取照片", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
